package cn.texous.easytalk.websocket.common.util;

import cn.texous.easytalk.websocket.model.entity.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/8/30 15:25
 */
@Component
public class MessageUtils {

    private static ObjectMapper OM;

    @Autowired
    private ObjectMapper objectMapper;

    @PostConstruct
    private void init() {
        OM = objectMapper;
    }

    /**
     * 将消息字符串转换为消息对象
     *
     * @param msgText msg
     * @param tClass target class
     * @param <T> type
     * @return return
     *
     * @throws Exception exctption
     *
     */
    public static <T> Message<T> textToMessage(String msgText, Class<T> tClass) throws Exception {
        return OM.readValue(msgText, new MessageTypeReference<>(tClass));
    }

    public static String messageToText(Object object) throws Exception {
        return OM.writeValueAsString(object);
    }

}
